<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    class MyPromise {
      constructor(handle) { // handle ---> (resolve,reject)=>{}
        this['[[PromiseState]]'] = "pedding";
        this['[[PromiseResult]]'] = undefined;
        handle(this.#_resolve.bind(this), this.#_reject.bind(this));
        this.resolveFn = undefined; // 保存 onResolved 函数
        this.rejectFn = undefined; // 保存onRejected函数
      }
      #_resolve (val) {  // 私有方法 需要在前面加上#号，只能类的内部调用外部不能调用
        // 外部的resolve函数
        // console.log(this);
        this['[[PromiseState]]'] = "fulfilled";
        this['[[PromiseResult]]'] = val;
        // 内容延迟执行
        setTimeout(() => {
          this.resolveFn(val); // 在调取resolve的时候执行，保存onResolved函数
        });
        let m = new MutationObserver(() => {
          this.resolveFn(val)
        })
        m.observe(document.body, {
          attributes: true
        })
        document.body.setAttribute("myattr", "val");
      }
      #_reject (err) {
        this['[[PromiseState]]'] = "rejected";  // 改变状态
        this['[[PromiseResult]]'] = val;    // 改变结果值
        setTimeout(() => {
          this.rejectFn(err);
        });
        setTimeout(() => {
          throw new Error(err);  // 抛出错误
        });
      }
      then (onResolved, onRejected) {
        console.log("then方法执行了");
        // onResolved  // 直接执行还不行
        this.resolveFn = onResolved;
        this.rejectFn = onRejected;
      }
    }

    // 执行顺序 会先执行 resolve函数 ,之后执行then方法 然后才赋值 onResolved 及onRejected
    setTimeout(() => {
      console.log("settimeout");
    });
    let p = new MyPromise((resolve, reject) => {
      resolve("success");
    })
    console.log(111);
    p.then(res => {
      console.log("执行了onResolved", res);
    }, err => {

    });  // 调用 类里的then方法；
    console.log(222);
  </script>
</body>

</html>